package cn.com.xy.sms.sdk.action;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import cn.com.xy.sms.sdk.constant.Constant;
import cn.com.xy.sms.sdk.log.LogManager;


public class NearbyPoint {

	private Activity mActivity;
	private SendMapQueryUrlThread mSendMapQueryUrlThread = null;
	private Handler mHandler;
	/**
	 * 收到百度地图检索结果
	 */
	public static final int QUERY_RESULT_RECEIVE = 0x1001;
	/**
	 * 地图检索参数错误
	 */
	public static final int QUERY_PARAM_ERROR = 0x1002;
	/**
	 * 参数错误无法生成百度地图检索Url
	 */
	public static final int GET_QUERY_URL_FAILURE = 0x1003;
	/**
	 * 百度地图检索url请求失败
	 */
	public static final int QUERY_REQUEST_ERROR = 0x1004;
	/**
	 * 执行获取定位位置经纬度
	 */
	public static final int DO_GET_LOCATION = 0x1005;
	/**
	 * Intent内存放检索结果的标识
	 */
	public static final String QUERY_RESULT = "queryResult";
	private double mLocationLatitude;// 所在位置纬度

	public double getLocationLatitude() {
		return mLocationLatitude;
	}

	private double mLocationLongitude;// 所在位置经度

	public double getLocationLongitude() {
		return mLocationLongitude;
	}

	private String mQuery;// 检索关键字
	private int mPageNum = 0; // 分页页码，默认为0,0代表第一页，1代表第二页，以此类推。

	public NearbyPoint(Activity activity, Handler handler) {
		mActivity = activity;
		mHandler = handler;
	}

	/**
	 * 在单独线程上进行发送圆形区域检索请求
	 */
	private class SendMapQueryUrlThread extends Thread {

		public void run() {
			try {
				// 地图检索参数错误
				if (mLocationLatitude < 0 || mLocationLongitude < 0 || mQuery == null || mQuery.equalsIgnoreCase("")) {
					mHandler.obtainMessage(QUERY_PARAM_ERROR).sendToTarget();
					return;
				}

				// 获取地图检索请求url
				String mapQueryUrl = createMapQueryUrl(mQuery, mLocationLatitude, mLocationLongitude, 20000, mPageNum);

				// 获取地图检索请求url失败
				if (mapQueryUrl == null) {
					mHandler.obtainMessage(GET_QUERY_URL_FAILURE).sendToTarget();
					return;
				}

				String queryResult = null;
				try {
					// 获取服务器返回的信息
					queryResult = HttpUtil.getRequest(mapQueryUrl);
				} catch (Throwable e) {
					// 百度地图检索url请求失败
					mHandler.obtainMessage(QUERY_REQUEST_ERROR).sendToTarget();
					return;
				}
	 
	            Message msg = mHandler.obtainMessage(QUERY_RESULT_RECEIVE);
	            Bundle bundle = new Bundle();
	            bundle.putString(QUERY_RESULT, queryResult);
	            msg.setData(bundle);
	            msg.sendToTarget();
			} catch (Throwable e) {
			    /*SDK-550 hewengao 20160719 start*/
				LogManager.w(Constant.TAG, e.getMessage(), e);
				 /*SDK-550 hewengao 20160719 end*/
			}
			
		}
	}

	/**
	 * 创建圆形区域检索请求url
	 * 
	 * @param query 检索关键字
	 * @param locationLat 周边检索中心点纬度
	 * @param locationLng 周边检索中心点经度
	 * @param radius 周边检索半径(米)
	 * @param pageNum 分页页码，默认为0,0代表第一页，1代表第二页，以此类推。
	 * @return 圆形区域检索请求url
	 */
	private String createMapQueryUrl(String query, double locationLat, double locationLng, int radius, int pageNum) {
		return createMapQueryUrl("6a0ddfcfdf1a1e7a1f38501fc5d218bf", query, locationLat, locationLng, radius, "json",
				2, pageNum);
	}

	/**
	 * 创建圆形区域检索请求url
	 * 
	 * @param key 用户的访问密钥
	 * @param query 检索关键字
	 * @param locationLat 周边检索中心点纬度
	 * @param locationLng 周边检索中心点经度
	 * @param radius 周边检索半径(米)
	 * @param output 检索结果输出格式(json或xml)
	 * @param scope 检索结果详细程度(1:基本信息 2:详细信息)
	 * @param pageNum 分页页码，默认为0,0代表第一页，1代表第二页，以此类推。
	 * @return 圆形区域检索请求url
	 */
	private String createMapQueryUrl(String key, String query, double locationLat, double locationLng, int radius,
			String output, int scope, int pageNum) {
		if (key == null || key.length() != 32 || query == null || locationLat < 0 || locationLng < 0 || radius < 1
				|| (!output.equalsIgnoreCase("json") && !output.equalsIgnoreCase("xml")) || (scope != 1 && scope != 2)) {
			return null;
		}

		StringBuffer sb = new StringBuffer();
		sb.append("http://android.bizport.cn:9998/AndroidWeb/getPlaceListAPI?");
		sb.append("query=");
        try {
            sb.append(URLEncoder.encode(query, "UTF-8"));
        } catch (UnsupportedEncodingException ex) {
//            ex.printStackTrace();
            /*SDK-550 hewengao 20160719 start*/
            LogManager.e(Constant.TAG, "createMapQueryUrl: " , ex);
            /*SDK-550 hewengao 20160719 end*/
        }
		sb.append("&lat=");
		sb.append(locationLat);
		sb.append("&lng=");
        sb.append(locationLng);
		sb.append("&radius=");
		sb.append(radius);
		sb.append("&scope=");
		sb.append(scope);
		sb.append("&page_num=");
		sb.append(pageNum);
		sb.append("&output=");
        sb.append(output);// 按距离从近到远排序
		return sb.toString();
	}

	/**
	 * 发送圆形区域检索请求
	 * 
	 * @param query 检索关键字
	 * @param latitude 所在位置纬度
	 * @param longitude 所在位置经度
	 * @param pageNum 分页页码，默认为0,0代表第一页，1代表第二页，以此类推。
	 */
	public void sendMapQueryUrl(String query, double latitude, double longitude, int pageNum) {
		if (mSendMapQueryUrlThread != null) {
			mSendMapQueryUrlThread.isInterrupted();
			mSendMapQueryUrlThread = null;
		}

		mQuery = query;
		mLocationLatitude = latitude;
		mLocationLongitude = longitude;
		mPageNum = pageNum;

		mSendMapQueryUrlThread = new SendMapQueryUrlThread();
		mSendMapQueryUrlThread.start();
	}

	static class HttpUtil {

		/**
		 * 
		 * @param url 请求地址
		 * @return 服务器响应的字符串
		 * @throws InterruptedException
		 * @throws ExecutionException
		 */
		public static String getRequest(final String strUrl) throws InterruptedException, ExecutionException,
				TimeoutException {
			FutureTask<String> task = new FutureTask<String>(new Callable<String>() {

				@Override
				public String call() throws Exception {
                    PrintWriter out = null;
                    BufferedReader in = null;
                    try {
                        URL realUrl = new URL(strUrl);
                        HttpURLConnection  conn =  (HttpURLConnection) realUrl.openConnection();  
                        conn.setRequestProperty("accept", "*/*");
                        conn.setRequestProperty("connection", "Keep-Alive");
                        conn.setRequestProperty("user-agent", "alitester");
                        conn.setRequestMethod("GET");
                        conn.setConnectTimeout(5000);
                        conn.setReadTimeout(5000);
                        conn.setDoOutput(true);
                        conn.setDoInput(true);
                        out = new PrintWriter(conn.getOutputStream());
                        /*SDK-646 zhaojiangwei 20161122 start */
                        if (out!=null) {
                        	 out.flush();
						}
                        in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                        String line;
                        StringBuffer result = new StringBuffer();
                        if (in!=null) {
                            while ((line = in.readLine()) != null) {
                                result.append(line);
                            }	
						}
                        /*SDK-646 zhaojiangwei 20161122 end */
                        return result.toString();
                    } catch (Throwable e) {
//                        e.printStackTrace();
                        /*SDK-550 hewengao 20160719 start*/
                        LogManager.w(Constant.TAG, "getRequest: ", e);
                        /*SDK-550 hewengao 20160719 end*/
                    } finally {
                        if (out != null) {
                            out.close();
                        }
                        if (in != null) {
                            try {
                                in.close();
                            } catch (IOException e) {
//                                e.printStackTrace();
                                LogManager.w(Constant.TAG, "getRequest: ", e);

                            }
                        }
                    }
                    return null;
				}
			});
			new Thread(task).start();
			return task.get(5000, TimeUnit.MILLISECONDS);
		}
	}
}
